package com.groupbuying.task.controller;

import com.google.common.base.Strings;
import com.groupbuying.task.config.UrlConstants;
import com.groupbuying.task.connector.RedPacketFeign;
import com.groupbuying.task.utils.HttpClientUtils;
import com.groupbuying.task.utils.apiresult.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author zmlmagic
 * @date 2019/10/8 11:58 AM
 * @company 蒙泰互联网公司
 * @des redpacket定时任务执行接口
 **/
@RequestMapping("/redpacket")
@RestController
public class RedpacketTaskController {
    private static final Logger logger = LoggerFactory.getLogger(RedpacketTaskController.class);

    @Value("${taskAccessToken:}")
    private String taskAccessToken;

    @Value("${task.startUrl}")
    private String startUrl;

    @Autowired
    private RedPacketFeign redPacketFeign;

    @Autowired
    private HttpClientUtils httpClientUtils;

    //创建，更新定时任务
    @GetMapping("/start")
    public Boolean start(@RequestParam Map<String, Object> params) {
        String accessToken = params.get("accessToken").toString();
        logger.info("请求参数：{}",params);
        if (Strings.isNullOrEmpty(accessToken) || !accessToken.equals(taskAccessToken)) {
            logger.info("非法访问");
            return false;
        }
        logger.info("请求成功，Id：{}", params.get("taskId") == null ? null : params.get("taskId"));
        // http调接口启动
        try {
            String result = httpClientUtils.doGet(startUrl, params);
            if (StringUtils.isEmpty(result)) {
                logger.error("任务：{},启动失败", params);
                return false;
            }
            logger.info("执行任务ID：{},任务启动结果:{}", params.get("taskId"), result);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @GetMapping("/stop")
    public Boolean stop(@RequestParam Map<String, Object> params) {
        String accessToken = params.get("accessToken").toString();

        if (Strings.isNullOrEmpty(accessToken) || !accessToken.equals(taskAccessToken)) {
            logger.info("非法访问");
            return false;
        }
        try {
            ApiResult result = redPacketFeign.delayStartTask(params.get("taskId") == null ? null : params.get("taskId").toString());
            logger.info("执行任务ID：{},任务启动结果:{}", params.get("taskId"), result);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
